package com.example.demo.security.filter;

import com.example.demo.security.userdetails.ManagerUserDetails;
import com.example.demo.unitls.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Security 基于JWT的token验证过滤器
 *
 * <pre>
 * 如果客户端Header中携带了token信息,则验证token信息；
 * 如果是一个合法的token 则将token信息转换为 Security UserDetails 存储到 Security 的上下文中
 * </pre>
 *
 * @author 叮当猫的百宝箱
 * @since 1.0
 */
@Slf4j
public class TokenFilter extends OncePerRequestFilter {

    private static final String REQUEST_HEADER_AUTHORIZATION = "Authorization";
    @Resource
    private TokenUtils tokenUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String bearerToken = request.getHeader(REQUEST_HEADER_AUTHORIZATION);
        try {
            UserDetails userDetails = tokenUtils.getUserDetailsByToken(bearerToken);
            if (userDetails != null) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails,
                        bearerToken,
                        userDetails.getAuthorities()
                );

                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }

        } catch (Exception e) {
            log.error("{}:{}", e.getClass().getName(), e.getMessage());
        }
        filterChain.doFilter(request, response);
    }
}
